package com.fdb.efp.flow.api.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fdb.efp.flow.service.FlowCommonService;
import com.fdb.basic.framework.core.constant.ApplicationConstance;
import com.fdb.basic.framework.core.constant.ResponseData;
import com.fdb.basic.framework.core.util.TimeUtil;
import com.fdb.basic.framework.core.vo.EngineHttpRequestVO;
import com.fdb.basic.framework.web.util.HttpClientUtil;
import com.fdb.basic.sequence.service.facade.SequenceService;
import com.fdb.efp.console.common.ConsoleConstant;
import com.fdb.efp.console.service.facade.PubSysInfoService;
import com.fdb.efp.e4a.service.facade.SRoleDataRuleService;
import com.fdb.efp.flow.common.constance.FlowConstance;
import com.fdb.efp.flow.executor.util.AbstractController;
import com.fdb.efp.flow.service.facade.BizFlowInfoService;
import com.fdb.efp.flow.service.facade.FlowUrlConfigService;
import com.fdb.efp.flow.service.vo.BizFlowInfoVO;
import com.fdb.efp.riskm.common.RiskColltConstant;
import com.fdb.efp.riskm.service.facade.ColltSmsNoticeAppService;
import com.fdb.efp.riskm.service.facade.ColltTaskFlowAppService;
import com.fdb.efp.riskm.service.facade.ColltTaskInfoService;
import com.fdb.efp.riskm.service.facade.ColltTaskRcdService;
import com.fdb.efp.riskm.service.vo.ColltSmsNoticeAppVO;
import com.fdb.efp.riskm.service.vo.ColltTaskFlowAppVO;
import com.fdb.efp.riskm.service.vo.ColltTaskInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 需求编号【2019D0509】
 *
 * 电话催收流程发起
 * @version 0.1 初始为0.1,后续变更则修改
 */
@RestController
@RequestMapping("/api")
public class ColltTaskTelForFlowController extends AbstractController {

    @Autowired
    @Qualifier("colltTaskRcdService")
    private ColltTaskRcdService colltTaskRcdService;

    @Autowired
    @Qualifier("sRoleDataRuleService")
    private SRoleDataRuleService sRoleDataRuleService;

    @Autowired
    @Qualifier("dbSeqService")
    private SequenceService sequenceService;

    @Autowired
    @Qualifier("colltTaskInfoService")
    private ColltTaskInfoService colltTaskInfoService;

    @Autowired
    @Qualifier("bizFlowInfoService")
    private BizFlowInfoService bizFlowInfoService;

    @Autowired
    @Qualifier("flowUrlConfigService")
    private FlowUrlConfigService flowUrlConfigService;

    @Autowired
    @Qualifier("pubSysInfoService")
    private PubSysInfoService pubSysInfoService;

    @Autowired
    @Qualifier("colltTaskFlowAppService")
    private ColltTaskFlowAppService colltTaskFlowAppService;

    @Autowired
    @Qualifier("colltSmsNoticeAppService")
    private ColltSmsNoticeAppService colltSmsNoticeAppService;

    @Autowired
    private FlowCommonService flowCommonService;


    /**
     * TODO: 流转任务 提交
     * @author
     * @params
     * @return
     */
    @PostMapping(value="/collt/task/flow/app/commit")
    public @ResponseBody ResponseData<Integer>  insertTaskFlowApp(@RequestBody ColltTaskFlowAppVO inColltTaskFlowAppVo) {
        int outputVo = 0;
        // 查询催收任务流转申请表判断是否存在审批中的流转申请信息
        ColltTaskFlowAppVO outputColltTaskFlowAppVO = null;
        setUserInfoToVO(inColltTaskFlowAppVo);
        List<ColltTaskFlowAppVO> list = new ArrayList<>();
        list.add(inColltTaskFlowAppVo);
        flowCommonService.displayUserName(list,"createUser","createUserName");
        List<ColltTaskFlowAppVO> queryRs = colltTaskFlowAppService.queryByColltTaskNo(inColltTaskFlowAppVo);
        if(queryRs.size()>0){
            for (ColltTaskFlowAppVO item : queryRs) {
                if (ConsoleConstant.APRV_STATUS_02.equals(item.getApproveStatus())) {
                    outputVo = -2;
                    return setResponseMessage(outputVo, "该催收任务存在“审批中”的流转申请，暂无法再次发起申请");
                }
            }
        }
        //  查询催收短信通知申请表判断是否存在审批中的短信通知申请信息
        ColltSmsNoticeAppVO outputColltSmsNoticeAppVO = null;
        ColltSmsNoticeAppVO inColltSmsNoticeAppVO = new ColltSmsNoticeAppVO();
        inColltSmsNoticeAppVO.setColltTaskNo(inColltTaskFlowAppVo.getColltTaskNo());
        List<ColltSmsNoticeAppVO> queryRss = colltSmsNoticeAppService.queryByColltTaskNo(inColltSmsNoticeAppVO);
        if(queryRss.size()>0){
            for (ColltSmsNoticeAppVO items : queryRss) {
                if (ConsoleConstant.APRV_STATUS_02.equals(items.getApproveStatus())) {
                    outputVo = -3;
                    return setResponseMessage(outputVo, "该催收任务存在“审批中”的短信通知申请，暂无法再次发起申请");
                }
            }
        }
        //  插入数据
        inColltTaskFlowAppVo.setCreateUser(inColltTaskFlowAppVo.getLoginUserId());
        inColltTaskFlowAppVo.setCreateTime(TimeUtil.getCurrentDateTime());
        inColltTaskFlowAppVo.setLastUpdateUser(inColltTaskFlowAppVo.getLoginUserId());
//        inColltTaskFlowAppVo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
        inColltTaskFlowAppVo.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
        inColltTaskFlowAppVo.setCreateUserOrg(inColltTaskFlowAppVo.getLoginUserOrgCode());
        try {
            String colltSeq = sequenceService.getSequence("CTFA_NO","null","null");
            inColltTaskFlowAppVo.setFlowApplyNo(colltSeq);
            outputVo = colltTaskFlowAppService.insertColltTaskFlowApp(inColltTaskFlowAppVo);
        } catch (Exception e) {
            logger.error("********************************************插入数据出错，异常信息为：", e.getMessage());
            outputVo = -1;
        }
        // 发起流程
        logger.info("即将发起电话催收人工流转审批流程，信息为:" + JSON.toJSONString(inColltTaskFlowAppVo));
        // 事件ID
        String eventId = "mColltTaskTelEnter";
        String flowId = "FW20190926000000005";

        inColltTaskFlowAppVo.setApproveStatus(ConsoleConstant.APRV_STATUS_02);
        inColltTaskFlowAppVo.setBasicColltTaskType(RiskColltConstant.STD_COLLT_WAY_01);

        BizFlowInfoVO bizFlowInfoVO = new BizFlowInfoVO();
        bizFlowInfoVO.setBizFlowType(FlowConstance.BIZ_FLOW_TYPE_10);
        bizFlowInfoVO.setBizFlowId(flowId);
        List<BizFlowInfoVO> listFlow = bizFlowInfoService.queryBizFlowInfoByFlowType(bizFlowInfoVO);
        // 获取流程ID
        logger.info("查询到的业务流程参数为："+ JSONObject.toJSONString(listFlow));
        if (Objects.nonNull(listFlow) && listFlow.size()>0) {
            bizFlowInfoVO = listFlow.get(0);
            flowId = bizFlowInfoVO.getBizFlowId();  // 得到业务流转ID
        } else {
            //提交失败 待发起
            inColltTaskFlowAppVo.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
            inColltTaskFlowAppVo.setBasicColltTaskType(null);
            colltTaskFlowAppService.updateByPk(inColltTaskFlowAppVo);
            outputVo = -1;
            return setResponseMessage(outputVo, "未配置相关信息提交失败!");
        }
        EngineHttpRequestVO eVo = new EngineHttpRequestVO();
        // 业务法人机构
        eVo.setBizLagelOrgCode(this.getUserInfo().getOrgInfo().getOrgCode());
        // 业务流水号
        eVo.setE_bizSerno(inColltTaskFlowAppVo.getFlowApplyNo());
        eVo.setFlowId(flowId);
        //事件ID
        eVo.setData(inColltTaskFlowAppVo);
        eVo.setEventId(eventId);
        eVo.setG_bizSerno(inColltTaskFlowAppVo.getFlowApplyNo());
        try {
            HttpClientUtil.callFlowEngine(flowUrlConfigService.getRestfulSyncStartEventUrl(), eVo, String.class);
            inColltTaskFlowAppVo.setLastUpdateUser(inColltTaskFlowAppVo.getLoginUserId());
            outputVo = colltTaskFlowAppService.updateByPk(inColltTaskFlowAppVo);

            //更新催收任务状态为"流转中"
            ColltTaskInfoVO colltTaskInfoVO = new ColltTaskInfoVO();
            colltTaskInfoVO.setColltTaskNo(inColltTaskFlowAppVo.getColltTaskNo());
            colltTaskInfoVO.setTaskSts("04");
            outputVo = colltTaskInfoService.updateByPk(colltTaskInfoVO);
        } catch (Exception e) {
            // 发起失败
            e.printStackTrace();
            logger.error("ColltTaskFlowAppVO", e.getMessage());
            outputVo = -1;
            return setResponseMessage(outputVo, "发起电话催收人工流转申请审批流程失败!原因: " + e.getMessage());
        }
        return getResponseData(outputVo);
    }

    private ResponseData<Integer> setResponseMessage(Integer outputVo, String message) {
        ResponseData<Integer> responseData = new ResponseData<Integer>();
        responseData.setMessage(message);
        responseData.setCode(ApplicationConstance.FAILURE);
        responseData.setSuccess(true);
        return responseData;
    }

    /**
     * TODO: 电话催收短信通知流程发起
     * @author
     * @params
     * @return
     */
    @PostMapping(value="/collt/task/tel/sms")
    public @ResponseBody ResponseData<Integer>  insertTaskFlowApp(@RequestBody ColltSmsNoticeAppVO colltSmsNoticeAppVO) {
        int outputVo = 0;
        //  查询催收短信通知申请表判断是否存在审批中的短信通知申请信息
        ColltSmsNoticeAppVO outputColltSmsNoticeAppVO = null;
        ColltSmsNoticeAppVO inColltSmsNoticeAppVO = new ColltSmsNoticeAppVO();
        inColltSmsNoticeAppVO.setColltTaskNo(colltSmsNoticeAppVO.getColltTaskNo());
        List<ColltSmsNoticeAppVO> queryRss = colltSmsNoticeAppService.queryByColltTaskNo(inColltSmsNoticeAppVO);
        if(queryRss.size()>0){
            for (ColltSmsNoticeAppVO items : queryRss) {
                if (ConsoleConstant.APRV_STATUS_02.equals(items.getApproveStatus())) {
                    outputVo = -3;
                    return setResponseMessage(outputVo, "该催收任务存在“审批中”的短信通知申请，暂无法再次发起申请");
                }
            }
        }
        // 查询催收任务流转申请表判断是否存在审批中的流转申请信息
        ColltTaskFlowAppVO colltTaskFlowAppVO = new ColltTaskFlowAppVO();
        colltTaskFlowAppVO.setColltTaskNo(colltSmsNoticeAppVO.getColltTaskNo());
        List<ColltTaskFlowAppVO> queryRs = colltTaskFlowAppService.queryByColltTaskNo(colltTaskFlowAppVO);
        if(queryRs.size()>0){
            for (ColltTaskFlowAppVO item : queryRs) {
                if (ConsoleConstant.APRV_STATUS_02.equals(item.getApproveStatus())) {
                    outputVo = -2;
                    return setResponseMessage(outputVo, "该催收任务存在“审批中”的流转申请，暂无法再次发起申请");
                }
            }
        }
        setUserInfoToVO(colltSmsNoticeAppVO);
        // 插入数据
        colltSmsNoticeAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
//        colltSmsNoticeAppVO.setCreateUser(colltSmsNoticeAppVO.getLoginUserId());
//        colltSmsNoticeAppVO.setCreateTime(TimeUtil.getCurrentDateTime());
        try {
            String smsSeq = sequenceService.getSequence("CTSMS_NO","null","null");
            colltSmsNoticeAppVO.setSmsNoticeApp(smsSeq);
            outputVo = colltSmsNoticeAppService.insertColltSmsNoticeApp(colltSmsNoticeAppVO);
        } catch (Exception e) {
            logger.error("********************************************插入数据出错，异常信息为：", e.getMessage());
            outputVo = -1;
        }
        // 发起流程
        logger.info("即将发起短信通知审批流程，信息为:" + JSON.toJSONString(colltSmsNoticeAppVO));
        // 事件ID
        String eventId = "mColltTaskTelSmsFlowEnter";
        String flowId = "FW20190926000000006";
        BizFlowInfoVO bizFlowInfoVO = new BizFlowInfoVO();
        bizFlowInfoVO.setBizFlowType(FlowConstance.BIZ_FLOW_TYPE_10);
        bizFlowInfoVO.setBizFlowId(flowId);
        List<BizFlowInfoVO> listFlow = bizFlowInfoService.queryBizFlowInfoByFlowType(bizFlowInfoVO);
        // 获取流程ID
        logger.info("查询到的业务流程参数为："+ JSONObject.toJSONString(listFlow));
        if (Objects.nonNull(listFlow) && listFlow.size()>0) {
            bizFlowInfoVO = listFlow.get(0);
            flowId = bizFlowInfoVO.getBizFlowId();  // 得到业务流转ID
        } else {
            //提交失败 待发起
            colltSmsNoticeAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
            colltSmsNoticeAppService.updateByPk(colltSmsNoticeAppVO);
            outputVo = -4;
            return setResponseMessage(outputVo, "未配置相关信息提交失败!");
        }
        EngineHttpRequestVO eVo = new EngineHttpRequestVO();
        // 业务法人机构
        eVo.setBizLagelOrgCode(this.getUserInfo().getOrgInfo().getOrgCode());
        // 业务流水号
        eVo.setE_bizSerno(colltSmsNoticeAppVO.getSmsNoticeApp());
        eVo.setFlowId(flowId);
        //事件ID
        eVo.setData(colltSmsNoticeAppVO);
        eVo.setEventId(eventId);
        eVo.setG_bizSerno(colltSmsNoticeAppVO.getSmsNoticeApp());
        try {
            HttpClientUtil.callFlowEngine(flowUrlConfigService.getRestfulSyncStartEventUrl(), eVo, String.class);
            colltSmsNoticeAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_02);
            colltTaskFlowAppVO.setLastUpdateUser(colltTaskFlowAppVO.getLoginUserId());
            outputVo = colltSmsNoticeAppService.updateByPk(colltSmsNoticeAppVO);

            //更新催收任务状态为“短信通知中”
            ColltTaskInfoVO colltTaskInfoVO = new ColltTaskInfoVO();
            colltTaskInfoVO.setColltTaskNo(colltTaskFlowAppVO.getColltTaskNo());
            colltTaskInfoVO.setTaskSts("05");
            outputVo = colltTaskInfoService.updateByPk(colltTaskInfoVO);
        } catch (Exception e) {
            // 发起失败
            e.printStackTrace();
            logger.error("ColltSmsNoticeAppVO", e.getMessage());
            outputVo = -5;
            return setResponseMessage(outputVo, "发起电话催收短信通知申请审批流程失败!原因: " + e.getMessage());
        }
        return getResponseData(outputVo);
    }
}
